/**
 * Flickr API Query module
 * @author Manel Villar 
 */

var flickrQuery = function() {
	var apiKey = "10a01be77af569cf0a61e61b19fb1dc8";
	var privacy = 1;
	var commons = 1;
	var license = "7";
	var per_page = 200;
	
	var baseQuery = 'http://api.flickr.com/services/rest/?';
	
	var set = {photos: {}, total: 0};

	function processPhotos(data, textStatus, callback) {
		set.photos = data.photos.photo;
		set.total = data.photos.total;
		console.log(set);
		
		if (typeof callback == "function") {
			callback(set);
		} 
	}
	
	return {
		/**
		 * Returns a photo data array
		 * @param {String} str
		 * @param {Function} callback
		 */
		getData: function(str, callback) {

			var query = baseQuery + '&method=flickr.photos.search&privacy_filter='+privacy+'&api_key=' + apiKey +'&per_page=' + per_page
			 + '&text=' + str + '&license=' + license + '&is_commons=' + commons + '&format=json&jsoncallback=?';

			var fn = function(data, textStatus) {
				processPhotos(data,textStatus,callback);
			};
			
			try {
				$.getJSON( query, fn);
			} catch (e) {
				console.log(e);
			}
		},
		
		getSizes: function(id, callback) {
			var query = baseQuery + '&method=flickr.photos.getSizes&photo_id='+id+'&api_key='+apiKey 
			 + '&format=json&jsoncallback=?';
			
			var fn = function(data, textStatus) {
				if (data.stat == "ok") {
					callback(data, textStatus);
				} else {
					console.log(data);
				}
			}
			
			try {
				$.getJSON( query, fn);
			} catch (e) {
				console.log(e);
			}
						
		},
		
		getInfo: function(id, callback) {
			var query = baseQuery + '&method=flickr.photos.getInfo&photo_id='+id+'&api_key='+apiKey 
			 + '&format=json&jsoncallback=?';
			
			var fn = function(data, textStatus) {
				if (data.stat == "OK") {
					callback(data, textStatus);
				} else {
					console.log(data);
				}
			}
			
			try {
				$.getJSON( query, fn);
			} catch (e) {
				console.log(e);
			}
						
		},
		
		/**
		 * get first Size that follows requirements
		 * @param {Object} data
		 * @param {Object} w
		 * @param {Object} h
		 * @return object or false if not found any match
		 */
		getBestSize: function(data, w, h) {
			var s = data.sizes.size;
			
			for (var k in s) {
				if (s[k].width >= w && s[k].height >= h) {
					return s[k];
				} 
			}
			
			return false;
		}
		 	
	}
}();
